<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  queryPermissionPageList,
  addPermission,
  updatePermission,
  deletePermission
} from '@/apis/permissionAPI'

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  permissionName: '',
  type: '',
  status: ''
})

// 权限列表数据
const permissionList = ref([])
const total = ref(0)
const loading = ref(false)

// 分页列表
const paginatedList = computed(() => permissionList.value)

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add') // add/edit

// 权限表单数据
const permissionForm = reactive({
  id: '',
  permissionName: '',
  permissionCode: '',
  type: 1,
  url: '',
  status: 1
})

// 表单引用
const permissionFormRef = ref(null)

// 页面加载时获取权限列表
onMounted(async () => {
  await loadPermissionList()
})

// 加载权限列表
const loadPermissionList = async () => {
  loading.value = true
  try {
    const res = await queryPermissionPageList(queryParams)
    permissionList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) {
    ElMessage.error(e.msg || '加载权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  loadPermissionList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  loadPermissionList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  loadPermissionList()
}

// 获取权限类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '菜单',
    2: '按钮',
    3: '接口'
  }
  return typeMap[type] || '未知'
}

// 获取权限类型标签样式
const getTypeTagType = (type) => {
  const typeTagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return typeTagMap[type] || 'info'
}

// 新增权限
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单
  Object.assign(permissionForm, {
    id: '',
    permissionName: '',
    permissionCode: '',
    type: 1,
    url: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(permissionForm, {
    id: row.id,
    permissionName: row.permissionName,
    permissionCode: row.permissionCode,
    type: row.type,
    url: row.url,
    status: row.status
  })
  dialogVisible.value = true
}

// 保存权限
const handleSave = async () => {
  // 表单验证
  await permissionFormRef.value.validate()

  try {
    if (dialogType.value === 'add') {
      await addPermission(permissionForm)
      ElMessage.success('新增成功')
    } else {
      await updatePermission(permissionForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    loadPermissionList()
  } catch (e) {
    ElMessage.error(e.msg || '操作失败')
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    // 这里假设有更新状态的API，如果没有需要自行实现
    // await updatePermissionStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (e) {
    row.status = row.status === 1 ? 0 : 1 // 失败回滚
    ElMessage.error(e.msg || '状态更新失败')
  }
}

// 删除权限
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限【${row.permissionName}】吗？`,
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deletePermission(row.id)
    ElMessage.success('删除成功')
    loadPermissionList()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error(e.msg || '删除失败')
    }
  }
}
</script>


<template>
  <div class="permission-container">
    <div class="permission-header">
      <div class="search-box">
        <el-select   v-model="queryParams.type" placeholder="权限类型" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="菜单" :value="1" />
          <el-option label="按钮" :value="2" />
          <el-option label="接口" :value="3" />
        </el-select>
        <el-select v-model="queryParams.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
      </div>
      <el-button  type="primary" @click="handleAdd" icon="Plus" > 新增权限</el-button>
    </div>
    <el-table :data="paginatedList" border style="width: 100%; margin-top: 20px;" v-loading="loading">
      <el-table-column prop="id" label="权限ID" width="100" align="center" />
      <el-table-column prop="permissionName" label="权限名称" width="180" align="center"/>
      <el-table-column prop="permissionCode"  label="权限代码" width="180" align="center"/>
      <el-table-column prop="type" label="权限类型" width="120" align="center" >
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)" > {{ getTypeText(scope.row.type) }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="url"  label="权限路径" align="center" />
      <el-table-column  prop="status"  label="状态"  width="120" align="center" >
        <template #default="scope">
          <el-switch v-model="scope.row.status"  :active-value="1"   :inactive-value="0"  @change="handleStatusChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"  width="180"  align="center" />
      <el-table-column   label="操作"  width="200" align="center"  >
        <template #default="scope">
          <el-button text @click="handleEdit(scope.row)"> 编辑 </el-button>
          <el-button text @click="handleDelete(scope.row)" type="danger" > 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog v-model="dialogVisible"  :title="dialogType === 'add' ? '新增权限' : '编辑权限'"  width="500px"  >
      <el-form  :model="permissionForm"  ref="permissionFormRef"  label-width="100px"  >
        <el-form-item label="权限名称"  prop="permissionName"  :rules="[{ required: true, message: '请输入权限名称', trigger: 'blur' }]"  >
          <el-input v-model="permissionForm.permissionName" />
        </el-form-item>
        <el-form-item  label="权限代码"  prop="permissionCode"  :rules="[{ required: true, message: '请输入权限代码', trigger: 'blur' }]"  >
          <el-input v-model="permissionForm.permissionCode" />
        </el-form-item>
        <el-form-item  label="权限类型"  prop="type"  :rules="[{ required: true, message: '请选择权限类型', trigger: 'change' }]" >
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
            <el-option label="接口" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item  label="权限路径"  prop="url"  >
          <el-input v-model="permissionForm.url" />
        </el-form-item>
        <el-form-item  label="状态"  prop="status"  >
          <el-radio-group v-model="permissionForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button  type="primary"  @click="handleSave"  >  确认  </el-button>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.permission-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin: 15px;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
}

.search-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.el-table {
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 500 !important;
}

.el-table tr:hover > td {
  background-color: #f9fafc !important;
}

.pagination {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
}

.el-button {
  transition: all 0.2s ease;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-dialog {
  border-radius: 6px;
  overflow: hidden;
}

.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.el-dialog__title {
  font-size: 16px;
  font-weight: 500;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  border-radius: 4px;
}
</style>
